import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

class PhoneSearchPage extends StatefulWidget {
  @override
  _PhoneSearchPageState createState() => _PhoneSearchPageState();
}

class _PhoneSearchPageState extends State<PhoneSearchPage> {
  final TextEditingController _controller = TextEditingController();
  late final List<String> _allPhones = _generateMockPhones();
  final Map<String, List<String>> _searchCache = {};
  OverlayEntry? _overlayEntry;
  final Debouncer _debouncer = Debouncer(delay: Duration(milliseconds: 300));

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('模糊搜索手机号')),
      body: Stack(
        children: [
          Column(
            children: [
              _buildSearchInput(),
            ],
          ),
          _buildResultsOverlay(),
        ],
      ),
    );
  }

  Widget _buildSearchInput() {
    return Padding(
      padding: EdgeInsets.all(16),
      child: TextField(
        controller: _controller,
        keyboardType: TextInputType.number,
        inputFormatters: [FilteringTextInputFormatter.allow(RegExp(r'^\d*'))],
        onChanged: (text) {
          _debouncer.run(() => _performSearch(text));
        },
        decoration: InputDecoration(
          hintText: '输入部分尾号',
          prefixIcon: Icon(Icons.phone),
          border: OutlineInputBorder(),
        ),
      ),
    );
  }

  Widget _buildResultsOverlay() {
    return Positioned(
      top: 80,
      left: 16,
      right: 16,
      child: Material(
        borderRadius: BorderRadius.circular(8),
        child: Padding(
          padding: const EdgeInsets.all(8.0),
          child: _searchCache.values.isNotEmpty
              ? ListView.builder(
            shrinkWrap: true,
            itemCount: _searchCache.values.first.length,
            itemBuilder: (context, index) => ListTile(
              title: Text(_searchCache.values.first[index]),
              onTap: () {
                _controller.text = _searchCache.values.first[index];
                _clearResults();
              },
            ),
          )
              : Text('无匹配结果'),
        ),
      ),
    );
  }

  void _performSearch(String query) {
    if (query.length < 3) {
      _clearResults();
      return;
    }

    final cacheKey = query.toLowerCase();
    if (_searchCache.containsKey(cacheKey)) {
      _showResults(_searchCache[cacheKey]!);
      return;
    }

    // 模拟网络请求延迟
    Future.delayed(Duration(milliseconds: 500)).then((_) {
      final results = _fuzzySearch(query);
      if (results.isNotEmpty) {
        setState(() {
          _searchCache[cacheKey] = results;
          _showResults(results);
        });
      }
    });
  }

  void _showResults(List<String> results) {
    _overlayEntry = _buildOverlay(results);
    Overlay.of(context)?.insert(_overlayEntry!);
  }

  void _clearResults() {
    _searchCache.clear();
    _overlayEntry?.remove();
    _overlayEntry = null;
  }

  List<String> _fuzzySearch(String query) {
    return _allPhones.where((phone) {
      final phoneStr = phone.replaceAll('-', '');
      return phoneStr.endsWith(query);
    }).toList();
  }

  OverlayEntry _buildOverlay(List<String> results) {
    return OverlayEntry(
      builder: (context) => Container(
        width: 200,
        padding: const EdgeInsets.all(8),
        height: results.length * 48.0,
        decoration: BoxDecoration(
          color: Colors.redAccent,
          borderRadius: BorderRadius.circular(8),
          boxShadow: [
            BoxShadow(
              color: Colors.grey.withOpacity(0.2),
              blurRadius: 4,
              offset: const Offset(0, 2),
            ),
          ],
        ),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: results.map((result) {
            return ListTile(
              title: Text(result),
              onTap: () {
                _controller.text = result;
                _clearResults();
              },
            );
          }).toList(),
        ),
      ),
    );
  }

  List<String> _generateMockPhones() {
    // 生成模拟数据（10000个手机号）
    final phones = <String>[];
    final prefixes = ['139', '138', '136', '188', '189'];
    for (var i = 0; i < 10000; i++) {
      final prefix = prefixes[i % prefixes.length];
      final numPart = (100000000 + i).toString().padLeft(8, '0');
      phones.add('$prefix$numPart');
    }
    return phones;
  }
}

class Debouncer {
  final Duration delay;
  Timer? _timer;

  Debouncer({required this.delay});

  void run(VoidCallback action) {
    _timer?.cancel();
    _timer = Timer(delay, action);
  }
}